import axios from 'axios';

import { baseRequestClient, requestClient } from '#/api/request';

/**
 * 保存
 */
export async function saveDocumentTemplateContentApi(param: any) {
  return requestClient.post<any>('document/template/save-content', param);
}

/**
 * 保存
 */
export async function loadDocumentTemplateContentByBizTypeApi(bizType: string) {
  return requestClient.get<any>(`document/template/content/${bizType}`);
}

export function saveDocumentDataApi(
  bizType: string,
  code: string,
  data: any,
): string {
  const key = `document-data:${bizType}:${code}`;
  sessionStorage.setItem(key, data);
  return key;
}

export function loadDocumentDataApi(key: string) {
  const printData = sessionStorage.getItem(key);
  if (printData) {
    return JSON.parse(printData);
  }
}

export async function loadDocumentTemplateRenderedApi(
  documentTemplateId: string,
  data: any = {},
  config?: any,
) {
  return baseRequestClient.post(
    `/document/template/render?documentTemplateId=${documentTemplateId}`,
    data || {},
    config,
  );
}

export async function documentTemplateRenderApi(
  documentTemplateId: string,
  renderData: any,
  config: any,
) {
  return axios({
    data: renderData,
    method: 'POST',
    responseType: 'blob',
    url: `${
      import.meta.env.VITE_GLOB_API_URL
    }/document/template/render?documentTemplateId=${documentTemplateId}`,
    headers: {
      ...config?.headers,
      'Content-Type': 'application/json',
    },
  });
}
